using System;

namespace RpgServiceLib.StoryFlagVariable
{
	

	public class StoryFlagVariable<T>:IStoryFlagVariable
	{
		public delegate void ChangedStoryFlagHandler (StoryFlagVariableChangeEvent questevent);
		public event ChangedStoryFlagHandler change;

		public string NameOfVariable {get; protected set;}
		protected T thisValue {get;set;}
		
		
		protected bool checkRightClassOfValue{get;set;}
	
		public StoryFlagVariable (string name, T startValue, bool throwExceptionIfWrongValue)
		{
			this.NameOfVariable = name;
			this.thisValue = startValue;
			this.checkRightClassOfValue=throwExceptionIfWrongValue;
		}
		
		public T Value 
		{ 
			get
			{
				return thisValue;
			} 
		}
		
		public StoryFlagVariableChangeEvent SetNewValue(T newVal)
		{
			if (newVal == null)
			{
				StoryFlagVariableChangeEvent changeEvent = new StoryFlagVariableChangeEvent (this, StoryFlagVariableChangeAllowType.IsNotAllowedWrongValue, thisValue, newVal);
				if (change != null) {
					change.Invoke (changeEvent);
				}				
				thisValue = newVal;	
				return changeEvent;			
			}
			
			if (thisValue.ToString() != newVal.ToString())
			{
					StoryFlagVariableChangeEvent changeEvent = new StoryFlagVariableChangeEvent (this, StoryFlagVariableChangeAllowType.IsAllowed, thisValue, newVal);
					if (change != null) {
						change.Invoke (changeEvent);
					}				
					thisValue = newVal;	
					return changeEvent;
			}
			return null;						
		}
		
		public override string ToString ()
		{
			return thisValue.ToString();			
		}
		
		public override int GetHashCode ()
		{
			return thisValue.GetHashCode ();
		}

		#region IStoryFlagVariable implementation
		public Type TypeOfFlagOrVariable {
			get {
				return thisValue.GetType();
			}
		}

		public object ValueAsObject {
			get {
				return thisValue as object;
			}
		}
		#endregion
	}
}

